package com.mreko.dashupload;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.widget.Toast;

public  class UploadFileUtil {
	private Context context;

	public UploadFileUtil(Context context) {
		super();
		this.context = context;
	}
	public UploadFileUtil() {
	}

	public int uploadFile(String srcPath) {
		int result = DashMessage.UPLOAD_UNSUCCEED;
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "******";
		try {
			URL url = new URL(DashMessage.SERVER_BASEURL+DashMessage.SERVER_UPLOAD);
			HttpURLConnection httpURLConnection = (HttpURLConnection) url
					.openConnection();
			// 设置每次传输的流大小，可以有效防止手机因为内存不足崩溃
			// 此方法用于在预先不知道内容长度时启用没有进行内部缓冲的 HTTP 请求正文的流。
			// 允许输入输出流
			httpURLConnection.setDoInput(true);
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setUseCaches(false);
			// use post
			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
			httpURLConnection.setRequestProperty("ENCTYPE",
					"multipart/form-data");
			httpURLConnection.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);
			httpURLConnection.setRequestProperty("file", srcPath);
			DataOutputStream dos = new DataOutputStream(
					httpURLConnection.getOutputStream());
			dos.writeBytes(twoHyphens + boundary + end);
			dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
					+ srcPath.substring(srcPath.lastIndexOf("/") + 1)
					+ "\""
					+ end);
			dos.writeBytes(end);
			FileInputStream fis = new FileInputStream(srcPath);
			System.out.println("FileInputStream:" + fis.available());
			byte[] buffer = new byte[512 * 1024]; // 512K
			int count = 0;
			// read files
			while ((count = fis.read(buffer)) != -1) {
				dos.write(buffer, 0, count);
			}
			fis.close();

			dos.writeBytes(end);
			dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
			dos.flush();

			int responseCode = httpURLConnection.getResponseCode();
			System.out.println("ResponseCode:" + responseCode);
			dos.close();
			/*Toast.makeText(context, "Upload Compelete", Toast.LENGTH_LONG)
					.show();*/
			if (responseCode == 200) {
				System.out.println("Upload Complete!");
				result = DashMessage.UPLOAD_SUCCEED;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

}
